﻿using System;
using Nardax.Azure.ServiceBus;
using Nardax.Samples.ServiceBus;

namespace Nardax.Samples.ServiceBusSubscriptionAdapter
{
    public class MessageProcessor
    {
        private readonly ISubscriptionAdapter<INardaxBrokeredMessage> _subscriptionAdapter;

        public MessageProcessor(ISubscriptionAdapter<INardaxBrokeredMessage> subscriptionAdapter)
        {
            _subscriptionAdapter = subscriptionAdapter;
        }

        public void ProcessMessages()
        {
            foreach (var message in _subscriptionAdapter.GetConsumingEnumerable())
            {
                var m = message;
                var count = m.GetBody<int>();
                Console.WriteLine("Receiving: {0}", count);
                m.BeginComplete((ar) =>
                    {
                        try
                        {
                            m.EndComplete(ar);
                        }
                        catch (Exception)
                        {
                            Console.WriteLine("EndComplete Exception");
                        }
                    }, null);
            }
        }

        public void Close()
        {
            _subscriptionAdapter.StopReceiving();
        }
    }
}